//
// Created by ruiyan on 2022/1/24.
//

#include "utils/UDPClient.h"

#include "define/DataDefine.h"

bool UdpClient::Start(const std::string &ip, const int &port, Recv_CallBack callBack) {
    int ret = init(ip, port);
    if (ret < 0) {
        return false;
    }
    struct sockaddr_in servAddr;
    bzero(&servAddr, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_port = htons(port);
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//    servAddr.sin_addr.s_addr = inet_addr(ip);

    if (bind(ret, (struct sockaddr *) &servAddr, sizeof(struct sockaddr)) != 0) {
        perror("binding err!");
        return false;
    }
    m_isStart = true;
    m_recvCallBack = callBack;

    m_recvThread = new std::thread(UdpClient::start_recvData, this);

    return false;
}

bool UdpClient::Stop() {
    m_isStart = false;
    return false;
}

int UdpClient::init(const std::string &ip, const int &port) {

    sock_Client = socket(AF_INET, SOCK_DGRAM, 0);//创建客户端用于通信的Socket
    if (sock_Client < 0) {
        GND_LOGD("socket(AF_INET, SOCK_DGRAM, 0) --------> error");
        return -1;
    }
    addr_server.sin_family = AF_INET;
    addr_server.sin_port = htons(port);//端口号为4567
    addr_server.sin_addr.s_addr = inet_addr(ip.c_str());   //127.0.0.1为本电脑IP地址

    return sock_Client;
}

bool UdpClient::WriteUdp(char *buf, int len) {
    int size = sendto(sock_Client, buf, len, 0, (sockaddr *) &addr_server, sizeof(sockaddr_in));
    GND_LOGD("ssendto return  --------> %d", size);
    return true;
}

void *UdpClient::start_recvData(void *pArgs) {
    auto *ptr = (UdpClient *) pArgs;
    ptr->udpRecvproc();
    return nullptr;
}

void UdpClient::udpRecvproc() {
    char array[1024];
    sockaddr sock;
    socklen_t len = sizeof(sock);
    while (m_isStart) {
        int s = recvfrom(sock_Client, array, sizeof(array) - 1, 0, (sockaddr *) &sock,
                         &len);
        if (s > 0) {
            if (m_recvCallBack != nullptr) {
                m_recvCallBack(array, s);
            }
        }
    }
}
